package com.lw.system.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.github.pagehelper.PageHelper;
import com.lw.common.core.dao.BaseDAO;
import com.lw.common.core.service.BaseService;
import com.lw.system.dao.MenuMapper;
import com.lw.system.model.Menu;
import com.lw.system.service.MenuService;

@Service("menuService")
public class MenuServiceImpl extends BaseService<Menu, String> implements MenuService {
	@Resource
	private MenuMapper menuMapper;

	@Override
	public BaseDAO<Menu, String> getDao() {
		return menuMapper;
	}

	@Override
	public Menu findMenuByProperties(Menu m) {
		return menuMapper.findMenuByProperties(m);
	}

	@Override
	public List<Menu> findAllTreeNode() {

		PageHelper.startPage(1, Integer.MAX_VALUE);
		List<Menu> menuList = menuMapper.findObjectsByPage();
		if (CollectionUtils.isNotEmpty(menuList)) {
			for (Menu m : menuList) {
				Map<String, Object> attributes = new HashMap<String, Object>();
				attributes.put("url", m.getUrl());
				m.setAttributes(attributes);
				getPMenu(m);
			}
		}
		return menuList;
	}

	private void getPMenu(Menu m) {
		if (!StringUtils.isEmpty(m.getPid())) {
			Menu pm = menuMapper.selectByPrimaryKey(m.getPid());// 获得当前节点的父节点对象
			if (pm != null) {
				m.setPid(pm.getId());
				m.setPname(pm.getText());
			}
		}
	}

	@Override
	public List<Menu> treegrid() {
		PageHelper.startPage(1, Integer.MAX_VALUE);
		List<Menu> l = menuMapper.findObjectsByPage();
		if (CollectionUtils.isNotEmpty(l)) {
			for (Menu m : l) {
				getPMenu(m);
			}
		}
		return l;
	}

	@Override
	public int remove(String id) {
		if (StringUtils.isEmpty(id)) {
			return 0;
		}
		return menuMapper.remove(id);

	}

	@Override
	public int add(Menu menu) {
		if (StringUtils.isEmpty(menu.getId())) {
			menu.setId(UUID.randomUUID().toString());
		}
		return menuMapper.insertSelective(menu);
	}

	@Override
	public int edit(Menu menu) {
		if (StringUtils.isEmpty(menu.getId())) {
			return 0;
		}
		return menuMapper.updateByPrimaryKeySelective(menu);
	}

}
